﻿using System;
using System.Collections.Generic;
using System.Windows.Threading;
using System.Threading;

namespace Hetymine.Executioner {
    public class CommandQueue : IDisposable {
        private object _Locker;
        private Thread _Worker;
        private Queue<string> _Queue;
        
        public CommandQueue() : this(string.Empty) { }
        public CommandQueue(string name) {
            this.Name = name;

            this._Locker = new object();
            this._Worker = new Thread(this.ExecuteCommands);
            this._Queue = new Queue<string>();

            this._Worker.Start();
        }

        public string Name { get; protected set; }

        public void EnqueueCommand(string command) {
            lock (this._Locker) {
                this._Queue.Enqueue(command);
                Monitor.Pulse(this._Locker);
            }
        }

        public void ExecuteCommands() {
            while (true) {
                string command;

                lock (this._Locker) {
                    while (this._Queue.Count == 0) {
                        Monitor.Wait(this._Locker);
                    }
                    command = this._Queue.Dequeue();
                }

                if (command == null) {
                    break; 
                }

                // Execute command
            }
        }        

        public void Dispose() {
            this.EnqueueCommand(null);
            this._Worker.Join();
        }
    }
}
